package ar.edu.caece.pl.asem.model.impl.treeelements;

import ar.edu.caece.pl.asem.temp.TemporalGenerator;

public class Asignacion extends AbstractElement {

	public Asignacion (){
		this.label = "ASIGNACION";
	}
	
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Asignacion))
			return false;
		Asignacion other = (Asignacion) obj;
		if (label == null) {
			if (other.label != null)
				return false;
		} else if (!label.equals(other.label))
			return false;
		return true;
	}


	@Override
	public void generateASMCode() {
		
		StringBuffer sb = new StringBuffer();
		String localContextName = this.getChildren().get(0).getEnvName();
		String id = localContextName + "_" + this.getChildren().get(0).getName();
		
		AbstractElement arrayNode = this.getChildren().get(0);
		if (arrayNode instanceof Arreglo) {
			//<EXPRESSION>
			arrayNode.parent = this;
			arrayNode.generateASMCode();
			sb.append(arrayNode.code);
			sb.append("\t mov di, offset " + id + "\n"); 
			sb.append("\t mov bx, ax \n");
			sb.append("\t mov ax, 2 \n");
			sb.append("\t mul bx \n");
			sb.append("\t add di, ax \n");

			this.getChildren().get(1).parent = this;
			this.getChildren().get(1).generateASMCode();
			sb.append(this.getChildren().get(1).code);
			sb.append("\t mov bx, ax \n");
			sb.append("\t mov [di], bx \n");
			TemporalGenerator.getInstance().releaseTemporal();
		} else {
			this.getChildren().get(1).parent = this;
			this.getChildren().get(1).generateASMCode();
			//<EXPRESSION>
			sb.append(this.getChildren().get(1).code);
			sb.append("\t mov " + id + ", ax \n");
			TemporalGenerator.getInstance().releaseTemporal();
		}
		this.code = sb.toString();
	}
}
